<?php

namespace app\admin\controller\medicine;

use app\common\controller\Backend;
use think\Db;
use fast\Auth;

/**
 * 药品报损
 *
 * @icon fa fa-circle-o
 */
class Breakages extends Backend
{

    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];
    protected $relationSearch = true;

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        //$this->model = new \app\admin\model\Medicine;
        $this->model = new \app\admin\model\Storage;

        $supplier = Db::table('fa_supplier')
            ->select();
        $this->view->assign("supplier", $supplier);
    }

    /**
     * 查看
     */
    public function index()
    {

        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                //->with(["medicine"=>['id','code','medicine_name','specification','supplier_name','model_number','type']])
                ->with([
                    'medicine' => function ($query) {
                        $query->withField('id,code,medicine_name,specification,supplier_name,model_number,type');
                    }
                ])
                ->where($where)
                ->where('medicine.is_del', 0)
                ->order('id', 'desc')
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }

        return $this->view->fetch();
    }


    /**
     * 详情
     */
    public function detail($ids)
    {


        //$row = $this->model->get(['id' => $ids]);
        $row = Db::table('fa_storage')
            ->alias('a')
            ->field('a.*,b.code,b.medicine_name')
            ->join('fa_medicine b','a.medicine_id=b.id','left')
            ->where(['a.id'=>['in',$ids]])
            ->order('a.id','desc')
            ->select();

        if (!$row) {
            $this->error(__('No Results were found'));
        }

        foreach ($row as $k=>$v){
            $row[$k]['create_time'] = date('Y-m-d H:i:s',$v['create_time']);
        }

        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 报损
     */
    public function edits(){
        //获取会员模型
        $user = $this->auth->getUserInfo();
        if ($this->request->isPost()) {
            $row = $this->request->post("row/a", [], 'trim');

            if ($row) {
                $arr = [];
                foreach ($row['counts'] as $k=>$v){
                    $arr[$k]['counts'] = $row['counts'][$k];
                    $arr[$k]['breakage_name'] = $user['nickname'];
                    $arr[$k]['msg'] = $row['msg'][$k];
                    $arr[$k]['create_time'] = time();
                    $arr[$k]['storage'] = $k;

                    $med = Db::table('fa_storage')
                        ->alias('a')
                        ->field('a.*,b.code,b.medicine_name')
                        ->join('fa_medicine b','a.medicine_id=b.id','left')
                        ->where('a.id',$k)
                        ->find();
                    if (($med['quantity']-$row['counts'][$k]) < 0){
                        $this->error(__($med['medicine_name'].'数量不足'));
                    }
                    $arr[$k]['medicine_id'] = $med['medicine_id'];


                }

                $arr = array_merge($arr);

                foreach ($arr as $k=>$v){
                    Db::table('fa_storage')
                        ->where('id',$v['storage'])
                        ->setDec('quantity',$v['counts']);

                    Db::table('fa_medicine')
                        ->where('id',$v['medicine_id'])
                        ->setDec('count',$v['counts']);

                    unset($arr[$k]['storage']);
                }


                $insert = Db::table('fa_breakage')
                    ->insertAll($arr);

                if ($insert > 0){
                    $this->success('成功');
                }else{
                    $this->error(__('失败'));
                }


            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
    }


}
